use salvo::prelude::*;
use utils::{app_error, response::*, success_response};

// 演示各种错误处理的Handler函数
#[handler]
async fn validation_error_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(validation, "用户输入验证失败：邮箱格式不正确"))
}

#[handler]
async fn business_error_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(business, "用户余额不足，无法完成交易"))
}

#[handler]
async fn not_found_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(not_found, "用户ID: 12345"))
}

#[handler]
async fn database_error_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(database, "数据库连接池已满"))
}

#[handler]
async fn network_error_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(network, "无法连接到支付网关"))
}

#[handler]
async fn timeout_error_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(timeout, "数据库查询超时，请重试"))
}

#[handler]
async fn unauthorized_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(unauthorized))
}

#[handler]
async fn external_service_error_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(external_service, "短信服务提供商返回错误"))
}

#[handler]
async fn configuration_error_demo() -> AppResult<ApiResponse<&'static str>> {
    Err(app_error!(configuration, "Redis连接配置无效"))
}

// 演示成功响应的Handler函数
#[handler]
async fn captcha_success() -> AppResult<ApiResponse<serde_json::Value>> {
    let data = serde_json::json!({
        "captcha_img": "...",
        "uuid": "123456789"
    });
    Ok(success_response!(data, "验证码生成成功"))
}

#[handler]
async fn user_info_success() -> AppResult<ApiResponse<serde_json::Value>> {
    let data = serde_json::json!({
        "user_id": 12345,
        "username": "张三",
        "email": "zhangsan@example.com",
        "phone": "13888888888",
        "status": "active"
    });
    Ok(success_response!(data))
}

#[handler]
async fn list_users_success() -> AppResult<ApiResponse<serde_json::Value>> {
    let data = serde_json::json!({
        "users": [
            {
                "user_id": 1,
                "username": "张三",
                "email": "zhangsan@example.com"
            },
            {
                "user_id": 2,
                "username": "李四",
                "email": "lisi@example.com"
            }
        ],
        "total": 2,
        "page": 1,
        "per_page": 10
    });
    Ok(success_response!(data, "用户列表获取成功"))
}

// 演示错误链的Handler函数
#[handler]
async fn error_chain_demo() -> AppResult<ApiResponse<&'static str>> {
    // 模拟IO错误并包装成数据库错误
    let io_err = std::io::Error::new(
        std::io::ErrorKind::ConnectionRefused,
        "Connection refused by database server",
    );
    Err(app_error!(database, "数据库连接失败", io_err))
}

#[handler]
async fn parse_error_demo() -> AppResult<ApiResponse<&'static str>> {
    // 模拟解析错误并包装成验证错误
    let parse_err = "invalid_number".parse::<i32>().unwrap_err();
    Err(app_error!(validation, "无效的数字格式", parse_err))
}

#[tokio::main]
async fn main() {
    // 初始化日志系统
    tracing_subscriber::fmt()
        .with_env_filter("error_demo=debug,salvo=info")
        .init();

    // 绑定服务器到端口 5800
    let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;

    // 创建路由器，包含多个错误演示端点
    let router = Router::new()
        // 错误演示端点
        .push(Router::with_path("validation-error").get(validation_error_demo))
        .push(Router::with_path("business-error").get(business_error_demo))
        .push(Router::with_path("not-found").get(not_found_demo))
        .push(Router::with_path("database-error").get(database_error_demo))
        .push(Router::with_path("network-error").get(network_error_demo))
        .push(Router::with_path("timeout-error").get(timeout_error_demo))
        .push(Router::with_path("unauthorized").get(unauthorized_demo))
        .push(Router::with_path("external-service-error").get(external_service_error_demo))
        .push(Router::with_path("configuration-error").get(configuration_error_demo))
        .push(Router::with_path("error-chain").get(error_chain_demo))
        .push(Router::with_path("parse-error").get(parse_error_demo))
        // 成功响应演示端点
        .push(Router::with_path("captcha").get(captcha_success))
        .push(Router::with_path("user-info").get(user_info_success))
        .push(Router::with_path("users").get(list_users_success));

    // 打印可用的端点
    println!("🚀 错误处理演示服务器启动于 http://localhost:5800");
    println!("📍 可用端点:");
    println!("  错误演示:");
    println!("    GET /validation-error       - 验证错误演示");
    println!("    GET /business-error         - 业务逻辑错误演示");
    println!("    GET /not-found              - 资源未找到错误演示");
    println!("    GET /database-error         - 数据库错误演示");
    println!("    GET /network-error          - 网络错误演示");
    println!("    GET /timeout-error          - 超时错误演示");
    println!("    GET /unauthorized           - 未授权错误演示");
    println!("    GET /external-service-error - 外部服务错误演示");
    println!("    GET /configuration-error    - 配置错误演示");
    println!("    GET /error-chain            - 错误链演示");
    println!("    GET /parse-error            - 解析错误链演示");
    println!("  成功响应演示:");
    println!("    GET /captcha                - 验证码生成演示");
    println!("    GET /user-info              - 用户信息获取演示");
    println!("    GET /users                  - 用户列表获取演示");
    println!("💡 提示: 设置环境变量 APP_ENV=development 查看详细错误信息");
    println!("💡 示例: APP_ENV=development cargo run --example error_demo");

    // 开始服务请求
    Server::new(acceptor).serve(router).await;
}
